import React from 'react';
import { Text, StyleSheet, View, Dimensions } from 'react-native';
import RootSiblings from 'react-native-root-siblings';

let toastInstance = null;

/**
 * 显示 Toast 的方法
 * @param {string} message - 要显示的消息内容
 * @param {number} duration - 显示的时间，单位毫秒（默认1500ms）
 */
export const showToast = (message, duration = 1500) => {
    if (toastInstance) {
        toastInstance.destroy();
    }

    toastInstance = new RootSiblings(
        <View style={styles.overlay}>
            <View style={styles.toastBox}>
                <Text style={styles.toastText}>{message}</Text>
            </View>
        </View>
    );

    // 自动销毁
    setTimeout(() => {
        hideToast();
    }, duration);
};

/**
 * 隐藏 Toast 的方法
 */
export const hideToast = () => {
    if (toastInstance) {
        toastInstance.destroy();
        toastInstance = null;
    }
};

const styles = StyleSheet.create({
    overlay: {
        position: 'absolute',
        top: 0,
        left: 0,
        width: Dimensions.get('window').width,
        height: Dimensions.get('window').height,
        justifyContent: 'center',
        alignItems: 'center',
        zIndex: 999999, // 确保层级足够高
        backgroundColor: 'transparent', // 保证背景透明
    },
    toastBox: {
        backgroundColor: 'rgba(0, 0, 0, 0.7)',
        paddingHorizontal: 20,
        paddingVertical: 10,
        borderRadius: 8,
        position: "relative",
        zIndex: 999999,
        maxWidth: '80%',
    },
    toastText: {
        color: '#fff',
        fontSize: 16,
        textAlign: 'center',
        lineHeight: 22,
    },
});
